package com.heart.house.api.service;

import com.google.common.collect.Lists;
import com.heart.house.api.dao.UserDao;
import com.heart.house.api.model.Agency;
import com.heart.house.api.model.User;
import com.heart.house.api.utils.BeanHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Luo Zhen
 * @create 2019-11-05 11:29
 */
@Slf4j
@Service
public class AccountService {

    @Value("${domain.name}")
    private String domainName;
    @Autowired
    private FileService fileService;
    @Autowired
    private UserDao userDao;

    public boolean isExist(String email) {
        return getUser(email) != null;
    }

    private User getUser(String email) {
        User queryUser = new User();
        queryUser.setEmail(email);
        List<User> users = getUserByQuery(queryUser);
        if (!CollectionUtils.isEmpty(users)) {
            return users.get(0);
        }
        return null;
    }

    private List<User> getUserByQuery(User queryUser) {
        return userDao.getUserList(queryUser);
    }

    public boolean addAccount(User account) {
        if (account.getAvatarFile() != null) {
            List<String> imags = fileService.getImgPath(Lists.newArrayList(account.getAvatarFile()));
            log.info("【头像地址】images:{}", imags.get(0));
            account.setAvatar(imags.get(0));
        }
        account.setEnableUrl("http://" + domainName + "/accounts/verify?key=");
        BeanHelper.setDefaultProp(account, User.class);
        BeanHelper.onInsert(account);
        userDao.addUser(account);
        return true;
    }

    public boolean enable(String key) {
        return userDao.enable(key);
    }

    public User auth(String username, String passwd) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(passwd)) {
            return null;
        }
        User user = new User();
        user.setEmail(username);
        user.setPasswd(passwd);
        try {
            user = userDao.authUser(user);
        } catch (Exception e) {
            return null;
        }
        return user;
    }

    public void logout(String token) {
        userDao.logout(token);
    }

    public List<Agency> getAllAgency() {
        return userDao.getAllAgency();
    }

    public User updateUser(User updateUser) {
        BeanHelper.onUpdate(updateUser);
        return userDao.updateUser(updateUser);
    }
}
